﻿using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using System.IO;
using System.Windows;

namespace HostWpfDemo
{

    public partial class App : Application
    {
        private readonly IHost host;
        private readonly ILogger<App> logger;
        public App()
        {
            host = CreateHostBuilder().Build();
            // ILogger<T>能够更好的追踪日志来源
            logger = host.Services.GetRequiredService<ILogger<App>>();
        }
        private static HostApplicationBuilder CreateHostBuilder()
        {
            // 创建HostApplicationBuilder，
            // Microsoft.Extensions.Hosting
            var builder = Host.CreateApplicationBuilder();
            //【1】配置JSON文件（自动包含appsettings.json和appsettings.{Environment}.json）
            // Configuration和DI在Hosting包中默认安装了
            // 清除默认源（可选）
            builder.Configuration.Sources.Clear();
            builder.Configuration
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true);
            //【2】配置日志（写入文件和控制台）
            builder.Logging.ClearProviders();
            //默认的Logg无法写入文件，清除自带logg配置，添加serilog
            //Serilog.Extensions.Hosting;Serilog.Sinks.File;Serilog.Sinks.Console
            builder.Logging.AddSerilog(new LoggerConfiguration()
                   .WriteTo.File("Logs/myapp-.log", rollingInterval: RollingInterval.Day)
                   .WriteTo.Console()
                   .CreateLogger());
            //【3】注册服务(DI默认已安装)服务注册必须在构建build之前完成
            builder.Services.AddSingleton<MainViewModel>();
            builder.Services.AddSingleton<MainWindow>(sp => new MainWindow()
            {
                DataContext = sp.GetRequiredService<MainViewModel>()
            });
            //【4】添加MVVM服务，如Message
            builder.Services.AddSingleton<WeakReferenceMessenger>();
            builder.Services.AddSingleton<IMessenger, WeakReferenceMessenger>(provider =>
                provider.GetRequiredService<WeakReferenceMessenger>());
            //添加其他服务如MessageBoxService、OpenfileService...
            //builder.Services.AddTransient<IMyService, MyService>();
            return builder;
        }
        protected override void OnStartup(StartupEventArgs e)
        {
            logger.LogInformation("应用程序启动!");
            try
            {
                host.Start();
                var mainWindow = host.Services.GetRequiredService<MainWindow>();
                mainWindow.Show();
                base.OnStartup(e);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "启动时发生错误");
                throw; // 抛出异常终止应用
            }
        }
        protected override void OnExit(ExitEventArgs e)
        {
            logger.LogInformation("应用程序关闭!");
            host.Dispose(); // 同步释放资源
            base.OnExit(e);
        }
    }
}
